package com.small.nacos.client.naming;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.small.nacos.client.naming.core.HostReactor;
import com.small.nacos.client.naming.net.NamingProxy;

import java.util.List;
import java.util.Properties;


/**
 * @Author zhoujin
 * @Date 2022/7/20 21:17
 */
public class NacosNamingService implements NamingService{

    private String namespace;

    private NamingProxy serverProxy;

    private String serverList;

    private HostReactor hostReactor;

    public NacosNamingService(Properties properties){
        init(properties);
    }

    private void init(Properties properties){
        this.serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
        this.namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
        this.serverProxy = new NamingProxy(this.namespace,this.serverList);
        this.hostReactor = new HostReactor(this.serverProxy);
    }

    @Override
    public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException {

        //注册服务
        String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName);

        serverProxy.registerService(groupedServiceName,groupName,instance);
    }

    @Override
    public List<Instance> getAllInstances(String serviceName, String groupName,List<String> clusters) throws NacosException {
       ServiceInfo serviceInfo = hostReactor
                .getServiceInfoDirectlyFromServer(NamingUtils.getGroupedName(serviceName,groupName),clusters);
        return serviceInfo.getHosts();
    }

    @Override
    public void deregisterInstance(String serviceName, String groupName, Instance instance) throws NacosException {
        serverProxy.deregisterService(NamingUtils.getGroupedName(serviceName, groupName), instance);
    }
}
